import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken, getRouter, setRouter } from '@/utils/cookie'
import { getRouters } from '@/api/user'
Vue.use(VueRouter)

const _import = require('@/router/_import_' + process.env.NODE_ENV) //获取组件的方法

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

/**
 * 导入布局组件
 */
import Layout from '@/layout'

/**
 * 白名单列表
 */
const whiteList = ['/login']
/**
 * 常量路由
 */
export const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: _import('login'),
    componentName: 'login',
    componentPath: 'login',
    hidden: true
  },
  {
    path: '',
    component: Layout,
    redirect: 'index',
    componentName: 'Layout',
    hidden: true,
    children: [
      {
        path: 'index',
        component: _import('index'),
        name: '首页',
        meta: { title: '首页', icon: 'dashboard' },
        componentName: 'index',
        componentPath: 'index',
        fullPath: '/index'
      }
    ]
  }
]
//存储后台获取到的路由
let routerList

const vueRouter = new VueRouter({
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

/**
 * 导航守卫
 */
vueRouter.beforeEach((to, from, next) => {
  const token = getToken()
  if (!token) {
    //没有token信息
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  } else {
    //有token信息
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (routerList) {
        next()
      } else {
        //再次从cookie中拿
        let routers = getRouter()
        if (routers) {
          routerList = routers
          routerGo(to, next)
        } else {
          //cookie中没有,从后台获取
          getRouters().then(res => {
            routerList = res
            setRouter(routerList)
            routerGo(to, next)
          })
        }
      }
    }
  }
})

/**
 * 过滤路由信息,并添加动态路由
 * @param {*} to
 * @param {*} next
 */
function routerGo(to, next) {
  routerList = filterAsyncRouter(routerList)
  console.log('添加的动态路由')
  console.log(routerList)
  vueRouter.addRoutes(routerList)
  next({ ...to, replace: true })
}

/**
 * 过滤路由信息
 * @param {*} asyncRouterMap
 */
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouter = asyncRouterMap.filter(route => {
    if (route.componentName) {
      if (route.componentName === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.componentPath)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouter
}

export default vueRouter
